package com.aurora.oa.message.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.message.adapter.ImageSelectAdapter;
import com.aurora.oa.message.bean.MessageData;
import com.aurora.oa.message.presenter.MessageSendActivityPresenter;
import com.aurora.oa.message.presenter.MessageSendActivityPresenterImpl;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.aurora.oa.work.bean.CompanyStructureBean;
import com.aurora.oa.work.view.CompanyStructureListActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/20 0020.
 */
public class MessageSendActivity extends AppCompatActivity implements MessageSendActivityView{

    private static final int GET_CONTACTS = 4;
    private static final int TAKE_PHOTO = 1 ;
    private static final int PICK_PHOTO = 2;
    private Toolbar toolbar;
    private EditText et_title;
    private EditText et_content;
    private RecyclerView rv_send_imgs ;
    private ImageSelectAdapter imageSelectAdapter;
    private LinearLayout ll_selector_bm,ll_selector_jt,ll_selector_gr;
    private TextView tv_jt,tv_bm,tv_gr;
    private MessageData messageData;
    private List<Uri> imageUri = new ArrayList<>();
    //文件上传成功服务器返回
    private List<String> uploadFileIDs;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private static final int SELECT_JT =0;
    private static  final int  SELECT_BM =1;
    private static final int SELECT_GR =2;
    MessageSendActivityPresenter messageSendActivityPresenter = new MessageSendActivityPresenterImpl(this);
    private Button bt_send;
    private ProgressDialog progressDialog;
    String type =null;
    private String userids;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_send);
        initTitleBar();
        initView();

    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch(requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString()+ File.separator+"aurora/image/"+name+".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile =new File(fileNmae);
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            if(!myCaptureFile.getParentFile().exists()){
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            Uri uri = Uri.fromFile(myCaptureFile);
                            imageUri.add(uri);
                            imageSelectAdapter.notifyDataSetChanged();
                            imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());

                        }else{

                            Toast toast= Toast.makeText(MessageSendActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    imageUri.add(uri);
                    imageSelectAdapter.notifyDataSetChanged();
                    imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());
                    break;
                case GET_CONTACTS:
                    userids = data.getExtras().getString("who_to_send_ids");/*
                    sendToIDs = data.getStringExtra("who_to_send_ids");
                    contactDatas.clear();
                    contactDatas.addAll((List<CompanyStructureBean.ChildNodeBean>) data.getSerializableExtra("contacts_list"));
                    personSelectAdapter.notifyDataSetChanged();
                    personSelectAdapter.notifyItemRemoved(personSelectAdapter.getItemCount());*/
                    break;
                default:
                    break;
            };
        }
    }

    private void initView() {
        et_title =(EditText)findViewById(R.id.et_title);
        et_content =(EditText)findViewById(R.id.et_content);
        ll_selector_bm = (LinearLayout) findViewById(R.id.ll_selector_bm);
        ll_selector_jt =(LinearLayout) findViewById(R.id.ll_selector_jt);
        ll_selector_gr =(LinearLayout) findViewById(R.id.ll_selector_gr);
        ll_selector_bm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setWhoToSendMessage(SELECT_BM);
            }
        });
        ll_selector_jt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setWhoToSendMessage(SELECT_JT);
            }
        });
        ll_selector_gr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setWhoToSendMessage(SELECT_GR);
            }
        });
        bt_send =(Button) findViewById(R.id.bt_send);
        bt_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                messageSendActivityPresenter.sendMessage();
            }
        });
        tv_jt = (TextView) findViewById(R.id.tv_jt);
        tv_bm= (TextView) findViewById(R.id.tv_bm);
        tv_gr= (TextView) findViewById(R.id.tv_gr);
        imageSelectAdapter = new ImageSelectAdapter(this,imageUri);
        imageSelectAdapter.setOnItemClickListener(new ImageSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(position==imageUri.size()){
                    //选择图片
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(MessageSendActivity.this, itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(MessageSendActivity.this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        rv_send_imgs = (RecyclerView) findViewById(R.id.rv_send_imgs);
        rv_send_imgs.setAdapter(imageSelectAdapter);
        rv_send_imgs.setLayoutManager(new GridLayoutManager(this,3));
        rv_send_imgs.setItemAnimator(new DefaultItemAnimator());
        rv_send_imgs.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));
    }

    private void setWhoToSendMessage(int i) {
        switch(i){
            case SELECT_JT:
                type = "1";
                userids = null;
                tv_jt.setTextColor(Color.RED);
                tv_bm.setTextColor(Color.BLACK);
                tv_gr.setTextColor(Color.BLACK);
                break;
            case SELECT_BM:
                type = "2";
                userids = null;
                tv_bm.setTextColor(Color.RED);
                tv_jt.setTextColor(Color.BLACK);
                tv_gr.setTextColor(Color.BLACK);
                break;
            case SELECT_GR:
                type=null;
                tv_gr.setTextColor(Color.RED);
                tv_bm.setTextColor(Color.BLACK);
                tv_jt.setTextColor(Color.BLACK);
                //跳转到通讯录列表选择人
                Intent intent =new Intent(MessageSendActivity.this, CompanyStructureListActivity.class);
                startActivityForResult(intent,GET_CONTACTS);
               // startActivityForResult(new Intent(MessageSendActivity.this,ContactsListActivity.class),GET_CONTACTS);
                break;
        }
    }

    private void initTitleBar() {
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab =getSupportActionBar();
        //把原始标题置空，显示自己的居中标题
        ab.setTitle("");
        ab.setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void onFilesUploadFail(String message) {
        ToastUtil.show(this,"文件上传失败："+message);
    }

    @Override
    public void onFilesUploadSuccess(String fileID) {
        ToastUtil.show(this,"文件上传成功："+fileID);

    }

    @Override
    public List<File> getImageFiles() {
        List<File> files = new ArrayList<>();
        for(int i = 0;i<imageUri.size();i++){
          File file =new File(UriUtils.getRealFilePath(this,imageUri.get(i)));
            files.add(file);
        }
        return files;
    }

    @Override
    public void showProgress() {

        progressDialog = ProgressDialog.show(this,null,"正在发送消息...");
    }

    @Override
    public void hideProgress() {
        progressDialog.dismiss();
    }

    /**
     *
     * @return 获取界面的消息数据
     */
    @Override
    public MessageData getMessageData() {
        MessageData messageData = new MessageData();
        messageData.name = et_title.getText().toString();
        messageData.content = et_content.getText().toString();
        messageData.type = type;

        messageData.userids = userids;
        return messageData;
    }

    @Override
    public void onMessageUploadSuccess() {
        ToastUtil.show(this,"消息发送成功");
        finish();
    }

    @Override
    public void onMessageUploadFail(String message) {
        ToastUtil.show(this,"消息上传失败"+message);

    }
}
